package com.sdksoft.readcard.utils.convertadapter;

import com.google.gson.Gson;
import com.google.gson.JsonIOException;
import com.google.gson.TypeAdapter;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonToken;

import java.io.IOException;

import okhttp3.ResponseBody;
import retrofit2.Converter;

final class GsonResponseBodyConverter<T> implements Converter<ResponseBody, T> {

    private final Gson gson;
    private final TypeAdapter<T> typeAdapter;

    GsonResponseBodyConverter(Gson gson, TypeAdapter<T> typeAdapter) {
        this.gson = gson;
        this.typeAdapter = typeAdapter;
    }

    @Override
    public T convert(ResponseBody value) throws IOException {
        try {
            try {
                JsonReader jsonReader = gson.newJsonReader(value.charStream());
                T result = typeAdapter.read(jsonReader);
                if (jsonReader.peek() != JsonToken.END_DOCUMENT) {
                    throw new JsonIOException("JSON document was not fully consumed.");
                }
                return result;
            } catch (Exception e){
                String string = value.string();
                if (string.endsWith("}") && !string.startsWith("{")) {
                    string = "{" + string;
                } else if (string.endsWith("]") && !string.startsWith("[")) {
                    string = "[" + string;
                }
                return (T) string;
            }
        } finally {
            value.close();
        }
    }
}